﻿#region Namespaces

using System.IO;
using System.Xml;
using System.Xml.Schema;

using Vibstudio.X4NET.Xml.Linq;

#endregion

namespace Vibstudio.X4NET.Xml.Schema
{
    public class XsdValidator
    {
        public static OperationResult Validate(string xml, string schemaUri, string targetNamespace = null)
        {
            XDocument document = XDocument.Load(XmlReader.Create(new StringReader(xml)));
            return Validate(document, schemaUri, targetNamespace);
        }

        public static OperationResult Validate(XDocument document, string schemaUri, string targetNamespace = null)
        {
            XmlSchemaSet schemaSet = new XmlSchemaSet();
            schemaSet.Add(targetNamespace == string.Empty ? string.Empty : targetNamespace, schemaUri);
            string validationMessage = string.Empty;
            bool isPerformed = true;
            document.Validate(schemaSet,
                              (o, e) =>
                              {
                                  validationMessage = e.Message;
                                  isPerformed = false;
                              });

            return isPerformed ? OperationResult.CreateSuccess() : OperationResult.CreateFailure(validationMessage);
        }
    }
}